<?php
	class GameAnswer{
		var $id;
		var $gameSessionId;
		var $leftColorName;
		var $rightColorName;
		var $shapeName;
		var $chosenColorName;
		var $time;
		
		public function GameAnswer($data=0){
			if(is_array($data)) $this->create($data);
			elseif(is_numeric($data)) $this->load($data);
		}
		
		public function load($id){
			$db = new HumeurDatabase();
			$data = mysql_fetch_assoc($db->query("SELECT * FROM gameAnswers WHERE answerId = '".$id."' LIMIT 1;"));
			$this->create($data);
		}
		
		public function create($array){
			$this->id = (isset($array['answerId']))? $array['answerId']:NULL;
			$this->gameSessionId = (isset($array['gameSessionId']))? $array['gameSessionId']:NULL;
			$this->leftColorName = (isset($array['leftColorName']))? $array['leftColorName']:NULL;
			$this->rightColorName = (isset($array['rightColorName']))? $array['rightColorName']:NULL;
			$this->shapeName = (isset($array['shapeName']))? $array['shapeName']:NULL;
			$this->chosenColorName = (isset($array['chosenColorName']))? $array['chosenColorName']:NULL;
			$this->time = (isset($array['time']))? $array['time']:NULL;
		}
		
		public function save(){
			if($this->id == NULL) return $this->insert();
			else return $this->update();
		}
		
		public function insert(){
			$db = new HumeurDatabase();
			$result = $db->query("INSERT INTO gameAnswers VALUES (NULL,'".$this->gameSessionId."','".$this->leftColorName."','".$this->rightColorName."','".$this->shapeName."','".$this->chosenColorName."','".$this->time."');");
			if($result){
				$this->id = mysql_insert_id();
			}
			return $result;
		}
		
		public function delete(){
			$db = new HumeurDatabase();
			return $db->query("DELETE FROM gameAnswers WHERE answerId = '".$this->id."';");
		}
		
		public function update(){
			return true;
		}
		
		public function summary(){
			return $this->chosenColorName;
		}
		
		public function draw($colorName){
			$db = new HumeurDatabase();
			$javascriptFunction = mysql_fetch_assoc($db->query("SELECT javascriptFunction FROM shapes WHERE shapeName = '".$this->shapeName."';"));
			$javascriptFunction = $javascriptFunction['javascriptFunction'];
			
			$color = mysql_fetch_assoc($db->query("SELECT * FROM colors WHERE colorName = '".$colorName."';"));
			$id = uniqid();
			return '<span id="'.$id.'"></span><script>document.getElementById("'.$id.'").appendChild('.$javascriptFunction.'('.$color['redQuantity'].','.$color['greenQuantity'].','.$color['blueQuantity'].',"'.uniqid().'",20))</script>';
		}
				
		public function __toString(){
			return '<div class="resultLine">Entre '.$this->draw($this->leftColorName)." et ".$this->draw($this->rightColorName).", vous avez choisi : ".$this->draw($this->chosenColorName)." en ".$this->time." ms.</div>";
		}
	}
?>